package starpay

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay/tool"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay/types"
)

type Params struct {
	MerchantRef string `json:"merchant_ref"`
	Product     string `json:"product"`
	Amount      string `json:"amount"`
	Extra       extra  `json:"extra"`
}
type extra struct {
	FiatCurrency string `json:"fiat_currency"`
	Address      string `json:"address"`
}
type Resp struct {
	Code      int    `json:"code"`
	Timestamp int64  `json:"timestamp"`
	Message   string `json:"message"`
	Params    string `json:"params"`
}

// 代收（充值）StarPay	url :请求url, merchantNo:商户号, merchantRef:订单号, secretKey, amount: 金额保留两位小数
func StarPay(url, merchantNo, merchantRef, secretKey, amount string) (resp Resp, err error) {
	// 请求第三方接口
	timestamp := time.Now().Unix()
	signType := types.MD5
	params := make(map[string]any)
	params["merchant_no"] = merchantNo
	params["timestamp"] = fmt.Sprintf("%d", timestamp)
	params["sign_type"] = signType
	var param = Params{
		MerchantRef: merchantRef,
		Product:     types.TRC20Buy,
		Amount:      amount,
		Extra: extra{
			FiatCurrency: types.INR,
		},
	}
	marshalparam, err := json.Marshal(&param)
	if err != nil {
		return resp, err
	}
	params["params"] = string(marshalparam)

	if v, err := tool.GenerateSignature(merchantNo, string(marshalparam), signType, secretKey, timestamp); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result Resp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Code != 200 {
		return resp, errors.New(result.Message)
	}
	return result, nil
}

// 出金（提现）StarWithDraw	url :请求url, merchantNo:商户号, merchantRef:订单号, secretKey, amount: 金额保留两位小数,address:地址
func StarWithDraw(url, merchantNo, merchantRef, secretKey, amount, address string) (resp Resp, err error) {
	// 请求第三方接口
	timestamp := time.Now().Unix()
	signType := types.MD5
	params := make(map[string]any)
	params["merchant_no"] = merchantNo
	params["timestamp"] = fmt.Sprintf("%d", timestamp)
	params["sign_type"] = signType
	var param = Params{
		MerchantRef: merchantRef,
		Product:     types.USDTTRC20Payout,
		Amount:      amount,
		Extra: extra{
			Address: address,
		},
	}
	marshalparam, err := json.Marshal(&param)
	if err != nil {
		return resp, err
	}
	params["params"] = string(marshalparam)

	if v, err := tool.GenerateSignature(merchantNo, string(marshalparam), signType, secretKey, timestamp); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result Resp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Code != 200 {
		return resp, errors.New(result.Message)
	}
	return result, nil
}

// 验签
func VerifiSign(merchantNo, params, signType, secretKey, sign string, reqTime int64) (bool bool, err error) {
	genSign, err := tool.GenerateSignature(merchantNo, params, signType, secretKey, reqTime)
	if sign != genSign {
		return false, err
	}
	return true, nil
}
